﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;

namespace Rizmar
{
    public partial class MainForm : Form
    {
        private Usuario user;

        static string cnStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        static SqlConnection cn = new SqlConnection(cnStr);
   
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            bool debug = true;

            if (debug && sender is MainForm) user = new Usuario("PROGRAMADOR", true);
            else
            {
                /* Abre a janela de login */
                LoginForm janela_login = new LoginForm(this);
                janela_login.ShowDialog();

                /* só pode abrir se o login for bem sucedido */
                if (janela_login.DialogResult != DialogResult.OK)
                    Application.Exit();
            }

            manutençãoToolStripMenuItem.Enabled = user.getAdmin();
            usuarioStatusLabel.Text = "Logado como " + user.getUsername();
        }

        public void SetUser(Usuario pessoa) { user = pessoa; }

        private void buttonCliente_Click(object sender, EventArgs e)
        {
            if (panelMostrarFormSec.Controls.Count > 0 && panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1] is Form)
                panelMostrarFormSec.Controls.Remove(panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1]);
            this.IsMdiContainer = true;
            ClienteForm novoForm = new ClienteForm();
            novoForm.MdiParent = this;
            panelMostrarFormSec.Controls.Add(novoForm);
            novoForm.Show();
        }

        private void buttonLançamento_Click(object sender, EventArgs e)
        {
            if (panelMostrarFormSec.Controls.Count > 0 && panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1] is Form)
                panelMostrarFormSec.Controls.Remove(panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1]);
            this.IsMdiContainer = true;
            LancamentoForm novoForm = new LancamentoForm();
            novoForm.MdiParent = this;
            panelMostrarFormSec.Controls.Add(novoForm);
            novoForm.Show();
        }

        private void buttonSacado_Click(object sender, EventArgs e)
        {
            if (panelMostrarFormSec.Controls.Count > 0 && panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1] is Form)
                panelMostrarFormSec.Controls.Remove(panelMostrarFormSec.Controls[panelMostrarFormSec.Controls.Count - 1]);
            this.IsMdiContainer = true;
            Sacado novoForm = new Sacado();
            novoForm.MdiParent = this;
            panelMostrarFormSec.Controls.Add(novoForm);
            novoForm.Show();
        }

        private void buttonSair_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void buttonCriaDB_Click(object sender, EventArgs e)
        {
            string cnnStr = @"Data Source=(local)\SQLEXPRESS; Integrated Security=SSPI";
            SqlConnection cnn = new SqlConnection(cnnStr);
            cnn.Open();

            /* 1.  COMANDOS */
            /* 1.1 Criar o banco de dados */
            string cria_db_string = @"
                CREATE DATABASE [Rizmar]
                ON PRIMARY
                    (NAME = N'Rizmar',
                    FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\Rizmar.mdf',
                    SIZE = 2304KB,
                    MAXSIZE = UNLIMITED,
                    FILEGROWTH = 1024KB)
                LOG ON
                    (NAME = N'Rizmar_log',
                    FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\Rizmar_log.ldf',
                    SIZE = 768KB,
                    MAXSIZE = UNLIMITED,
                    FILEGROWTH = 10%)
                COLLATE Latin1_General_CI_AS";
            /* 1.2 Criar tabelas */
            string tabela_titulo_string = @"
                CREATE TABLE [dbo].[Titulo] (
                    [id] int NOT NULL ,
                    [cliente_id] int NOT NULL ,
                    [sacado_id] int NOT NULL ,
                    [codigo] nvarchar(20) NOT NULL ,
                    [valor] real NOT NULL ,
                    [tipo] bit NOT NULL ,
                    [banco] nvarchar(20) NOT NULL ,
                    [data_base] date NOT NULL ,
                    [vencimento] date NOT NULL ,
                    [dias] int NULL ,
                    [d] int NULL ,
                    [desagio] real NULL ,
                    [liquido] real NULL ,
                    [tipo_servico] bit NOT NULL ,
                    [status] bit NOT NULL ,
                    PRIMARY KEY ([id])
                )";
            string tabela_cliente_string = @"
                CREATE TABLE [dbo].[Cliente] (
                    [id] int NOT NULL ,
                    [nome] nvarchar(50) NOT NULL ,
                    [documento] nvarchar(20) NOT NULL ,
                    [email] nvarchar(50) NULL ,
                    [telefone] nvarchar(20) NULL ,
                    [celular] nvarchar(20) NULL ,
                    [logradouro] nvarchar(50) NOT NULL ,
                    [numero] int NOT NULL ,
                    [bairro] nvarchar(20) NOT NULL ,
                    [cep] nvarchar(10) NOT NULL ,
                    [cidade] nvarchar(20) NOT NULL ,
                    [estado] nvarchar(2) NOT NULL ,
                    [limite] real NULL ,
                    [taxa] real NOT NULL ,
                    [d] int NULL ,
                    [status] bit NOT NULL ,
                    PRIMARY KEY ([id])
                )";
            string tabela_sacado_string = @"
                CREATE TABLE [dbo].[Sacado] (
                    [id] int NOT NULL ,
                    [nome] nvarchar(50) NOT NULL ,
                    [documento] nvarchar(20) NOT NULL ,
                    [email] nvarchar(50) NULL ,
                    [telefone] nvarchar(20) NULL ,
                    [celular] nvarchar(20) NULL ,
                    [logradouro] nvarchar(50) NOT NULL ,
                    [numero] int NOT NULL ,
                    [bairro] nvarchar(20) NOT NULL ,
                    [cep] nvarchar(10) NOT NULL ,
                    [cidade] nvarchar(20) NOT NULL ,
                    [estado] nvarchar(2) NOT NULL ,
                    [status] bit NOT NULL ,
                    PRIMARY KEY ([id])
                )";
            string tabela_taxa_string = @"
                CREATE TABLE [dbo].[Taxa] (
                    [pis_cofins] real NOT NULL ,
                    [irpj] real NOT NULL ,
                    [iof] real NOT NULL ,
                    [iss] real NOT NULL 
                )";
            using (SqlCommand cria_db_comando = new SqlCommand(cria_db_string, cnn))
            {
                bool basecriada = true;
                try
                {
                    cria_db_comando.ExecuteNonQuery();
                }
                catch (SqlException)
                {
                    MessageBox.Show("Base de dados já existente. Não é necessário criá-la novamente.");
                    basecriada = false;
                }
                cnn.Close();
                if (basecriada)
                {
                    cn.Open();

                    using (SqlCommand tabela_titulo_comando = new SqlCommand(tabela_titulo_string, cn))
                    {
                        tabela_titulo_comando.ExecuteNonQuery();
                        using (SqlCommand tabela_cliente_comando = new SqlCommand(tabela_cliente_string, cn))
                        {
                            tabela_cliente_comando.ExecuteNonQuery();
                            using (SqlCommand tabela_sacado_comando = new SqlCommand(tabela_sacado_string, cn))
                            {
                                tabela_sacado_comando.ExecuteNonQuery();
                                using (SqlCommand tabela_taxa_comando = new SqlCommand(tabela_taxa_string, cn))
                                {
                                    tabela_taxa_comando.ExecuteNonQuery();
                                    MessageBox.Show("Base de dados criada com sucesso!", "Sucesso");
                                }
                            }
                        }
                    }
                }
            }
            cn.Close();
        }

        private void buttonTaxas_Click(object sender, EventArgs e)
        {
            TaxasForm janela = new TaxasForm();
            janela.Show();
        }

        private void buttonUsuarios_Click(object sender, EventArgs e)
        {
            UsuarioForm janela = new UsuarioForm();
            janela.Show();
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm_Load(MainMenuStrip, null);
        }
    }
}
